package ch.bfh.aufs.prologparser.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Observable;

import ch.bfh.aufs.prologparser.utils.TokenFormatter;

public class PPController extends Observable {

    private File file;
    private ArrayList<String> tokens;
    private PPTokenizer tokenizer;
    private TokenFormatter formatter;

    public PPController() {
        tokenizer = new PPTokenizer();
        formatter = new TokenFormatter();
    }

    public void setFile(File file) {
        this.file = file;

    }

    public void parsePrologFile() {

        String line = "";
        tokens = new ArrayList<String>();
        if (file != null) {
            try {

                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                while ((line = br.readLine()) != null) {
                    ArrayList<String> tt = tokenizer.getTokens(line);

                    if (tt != null) {
                        tokens.add(formatter.spaceSeparator(tt));
                    }
                }
                br.close();
            } catch (Exception e) {
                System.out.println("Ex: " + e.getMessage());
            }
        } else {
            System.out.println("File is Null");
        }
        setChanged();
        notifyObservers(tokens);
        clearChanged();
    }

    public void createOutputFile(File of) {
        try {
            PrintWriter printWriter = new PrintWriter(of);
            for (String s : tokens) {
                printWriter.println(s);
            }
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("bubu");
    }

}
